﻿using MailKit.Net.Smtp;
using Microsoft.Extensions.Configuration;
using MimeKit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WomanMotion.WebApi.Infrastructure.Email
{
    /// <summary>
    /// 邮件发送
    /// </summary>
    public class SendMail : ISendMail
    {
        /// <summary>
        /// 配置文件读取
        /// </summary>
        private readonly IConfiguration _configuration;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configuration"></param>
        public SendMail(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 发送Email
        /// </summary>
        /// <param name="message">消息体</param>
        /// <param name="name">收件人</param>
        /// <param name="addressee">收件地址</param>
        /// <returns></returns>
        public async Task SendEmailAsync(MimeMessage message, string name, string addressee)
        {
            //获取配置文件
            var mailconfigMoble = _configuration.GetSection("Email").Get<MailConfigModel>();
            var host = mailconfigMoble.host;
            var port = mailconfigMoble.port;
            var useSsl = mailconfigMoble.useSsl;
            var from_username = mailconfigMoble.from_username;
            var from_password = mailconfigMoble.from_password;
            var from_name = mailconfigMoble.from_name;
            var from_address = mailconfigMoble.from_address;

            var address = new List<MailboxAddress>
            {
                new MailboxAddress(name,addressee)
            };

            message.From.Add(new MailboxAddress(from_name, from_address));
            message.To.AddRange(address);

            using var client = new SmtpClient
            {
                ServerCertificateValidationCallback = (s, c, h, e) => true
            };
            client.AuthenticationMechanisms.Remove("XOAUTH2");

            await client.ConnectAsync(host, port, useSsl);
            await client.AuthenticateAsync(from_username, from_password);
            await client.SendAsync(message);
            await client.DisconnectAsync(true);
        }
    }
}